#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef pair<int, int> PII;


const int N = 150010;
int d[N], e[N], ne[N], h[N], idx;
int dist[N], n, m;
bool st[N];
int Dijkstra(){
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    dist[1] = 0;
    heap.push({0, 1});
    while(!heap.empty()){
        PII temp = heap.top();
        heap.pop();
        int point = temp.second, wei = temp.first;
        if(st[point])continue;
        st[point] = true;
        for(int i = h[point]; i != -1; i = ne[i]){
            if(dist[e[i]] > dist[point] + d[i]){
                dist[e[i]] = dist[point] + d[i];
                heap.push({dist[e[i]], e[i]});
            }
        }
    }
    return dist[n] == 0x3f3f3f3f ? -1 : dist[n];
    
    
}
void add(int a, int b, int c){
    e[idx] = b;
    d[idx] = c;
    ne[idx] = h[a];
    h[a] = idx++;
}

void init(){
    memset(h, -1, sizeof(h));
    memset(dist, 0x3f, sizeof(dist));
}
int main(){
    init();
    cin>>n>>m;
    int a, b, c;
    while(m--){
        cin>>a>>b>>c;
        add(a, b, c);
    }
    cout<<Dijkstra()<<endl;
}